package com.pmstation.skin

import java.awt.image.BufferedImage
import javax.imageio.ImageIO
import java.io.File
import scala.math._
import java.awt.Color
import collection.mutable

/**
 * Created by IntelliJ IDEA.
 * User: denny
 * Date: Jul 7, 2010
 * Time: 3:14:51 PM
 * To change this template use File | Settings | File Templates.
 */

object EdgesByDiff{
  def main(args:Array[String]){
    EdgesByDiff.paintDiffImg()
  }

  //val imgFile =  "/image/edge/apple-leafs.jpg"
  val imgFile =  "/test1.jpg"
  //val imgFile =  "/image/edge/apple-leafs_blur.jpg"

  val imgStream = getClass.getResourceAsStream(imgFile)
  val img : BufferedImage = ImageIO.read(imgStream)


  def paintDiffImg(){
    val imgDiff = new BufferedImage(img.getWidth, img.getHeight, img.getType)
    //val imgBlur = GaussianBlur.blur(img, 20, 5);

    val dhisto = new mutable.HashMap[Int,Int]

    var max=0
    for( x <- 0 until img.getWidth ){
      //println("diff x="+x)
      for( y <- 0 until img.getHeight ){
        //val d = colorDiff(imgBlur , XY(x,y), 2)
        val d = colorDiff(img , XY(x,y), 2)
        dhisto(d) = dhisto.getOrElse(d,0)+1
        if( y==img.getHeight/2 ){
          println("x=%3s  d=%3s  %s".format(x,d, "o"*(d/3) ))
        }
        max = max.max(d)
        imgDiff.setRGB(x, y, d)
      }
    }


    for( x <- 0 until img.getWidth ){
      //println("diff x="+x)
      for( y <- 0 until img.getHeight ){
        //imgDiff.setRGB(x, y, colorDiff(img , XY(x,y), 2))
        val oldC = imgDiff.getRGB(x,y) & 0xffffff
        val c = 255*oldC/max
        if( c>255 ){
          println(c)
        }
        imgDiff.setRGB(x, y, c)
//        if( y==img.getHeight/2 ){
//          imgDiff.setRGB(x, y, Color.YELLOW.getRGB)
//        }
        if( oldC>50 ){
          imgDiff.setRGB(x, y, Color.RED.getRGB)
        }else{
          imgDiff.setRGB(x, y, 0)
        }
      }
    }

    val f = new File("/tmp/skin_diff.jpeg")
    ImageIO.write(imgDiff, "jpeg", f)
    println("%s ready max=%s".format(f,max))

    for( (d,count) <- dhisto.toList.sortBy(_._1) ){
      println("d=%3s count=%s".format(d, count))
    }
  }

  def colorDiff(imgForDiff:BufferedImage, p:XY, r:Int):Int ={
    //val diff = new ColorDiff
    val diff = new ColorDiffCos
    for(x <- (p.x - r) to (p.x + r) ){
      // println (x)
      for(y <- (p.y - r) to (p.y + r) ){
        if( (p.x-x)*(p.x-x) + (p.y-y)*(p.y-y) <= r*r ){
          if( x>=0 && y>=0 && x<imgForDiff.getWidth && y<imgForDiff.getHeight ){
            diff.update(imgForDiff.getRGB(x,y))
          }
        }
      }
    }
    (diff.maxDiff*200).toInt
  }
  
} 